<template>
  <div class="md:card w-full md:max-w-md md:shadow-2xl md:bg-base-100/80">
    <div class="md:card-body">
      <!-- 标题区域 -->
      <div class="text-center">
        <div class="avatar avatar-placeholder">
            <div class="w-20 rounded-full bg-primary text-primary-content flex items-center justify-center">
             <font-awesome-icon icon="user-circle" size="8x"></font-awesome-icon>
            </div>
          </div>
        <h1 class="text-3xl font-bold text-primary">欢迎回来</h1>
        <p class="text-base-content/70 mt-2">请输入您的账号信息登录系统</p>
      </div>

      <!-- 登录表单 -->
      <Form ref="form" v-slot="{ errors }" @submit="postLogin">
        <div class="space-y-2">
          <edit-item 
              key-name="username"
              v-model="row.username"
              :options="{name:'用户名', rules: 'required|user_name',icon:'user'}">   
              <template #default="props">
                <font-awesome-icon icon="user"></font-awesome-icon>
                <input
                  name="username"
                  autocomplete="username"
                  type="text"
                  v-bind="props.field"
                  :placeholder="props.placeholder" />  
              </template>     
          </edit-item>
          <edit-item 
            key-name="password"
            v-model="row.password"
            :options="{name:'密码', rules: 'required|min:6|max:18'}">    
            <template #input-item="props">
              <password-edit v-bind="props.field" icon="lock" :class="{'input-error':props.errorMessage}" />
            </template>    
          </edit-item>
           <edit-item 
            v-if="must_verify"
            key-name="verify"
            v-model="row.verify"
            :options="{name:'验证码', rules: 'required|captcha'}">    
            <template #input-item="props">
              <label class="input w-full" :class="{'input-error':props.errorMessage}">
                <input type="text" v-bind="props.field" placeholder="请输入验证码" />
                <span class="label">
                  <captcha-img ref="captchaImg" v-model="row.captcha_key" class="h-full"></captcha-img>
                </span>
              </label>
            </template>    
          </edit-item>
          <edit-item 
            v-if="must_verify"
            v-show="false"
            key-name="captcha_key"
            v-model="row.captcha_key"
            :options="{name:'验证码KEY'}">                   
          </edit-item>
          <!-- 记住我和忘记密码 -->
          <div class="flex items-center justify-between">
            <Field name="remember" 
            v-model="row.remember"
             v-slot="{ field, errors, errorMessage }"
             >
              <label class="cursor-pointer label">
                <input type="checkbox" 
                :class="errorMessage?'checkbox-error':''"
                class="checkbox checkbox-sm" 
                :value="1"
                v-bind="field"  />
                <span class="label-text ml-2 text-sm" :class="errorMessage?'text-error':''">记住我</span>
              </label>
            </Field>
            <router-link class="link link-primary" to="/guest/password/forgot">忘记密码?</router-link>
          </div>
          <p class="text-error" v-show="errors.agree">
              {{errors.agree}}
          </p>
          <button class="btn btn-primary mt-4 w-full" type="submit" :disabled="sending">
            <span v-if="sending" class="loading loading-spinner loading-xs ml-1"></span>
            <font-awesome-icon v-else icon="sign-in"></font-awesome-icon>
            登录
          </button>
        </div>
      </Form>

      <!-- 分隔线 -->
      <div class="divider my-5">或者</div>

      <!-- 社交登录选项 -->
      <div class="grid gap-4" :class="other_login_items.length<3?'grid-cols-'+(other_login_items.length+1):'grid-cols-3'">
         <router-link to="/guest/login/code" class="btn btn-outline btn-accent">
          <font-awesome-icon icon="fa-solid fa-envelope"></font-awesome-icon>
          <span class="ml-2">验证码</span>
        </router-link>
        <a v-for="(login_item,index) in other_login_items"
          :href="configStore.config.app_url+'/web-api'+login_item.url" 
          class="btn btn-outline"
          :class="(login_item.class || '').replace('hover-','btn-')"
          >
          <font-awesome-icon :icon="'fa-brands fa-'+login_item.type"></font-awesome-icon>
          <span class="ml-2">{{ login_item.type }}</span>
        </a>
      </div>
      <div v-for="(item,index) in other_login_btn_items" :class="'other-'+item.type" :ref="'other-'+item.type">
      </div>
      

      <!-- 注册链接 -->
      <div class="text-center mt-8">
        <p class="text-sm text-base-content/70">
          还没有账号?
          <router-link class="link link-primary" to="/guest/register">立即注册</router-link>
        </p>
      </div>
    </div>
  </div>

</template>
<script>
import {editItem,passwordEdit,captchaImg} from '@/extensions/components'
import { Form,Field } from 'vee-validate';
import {useUserStore} from '@/stores/user'
import {useConfigStore} from '@/stores/config'
import collect from 'collect.js';

const userStore = useUserStore();
const configStore = useConfigStore();
export default {
  components: {
    Form,
    Field,
    editItem,
    passwordEdit,
    captchaImg
  },
  data() {
    return {
      userStore,
      configStore,
      sending:false,
      row:{
        username:'',
        password:'',
        verify:'',
        captcha_key:'',
        remember:0,
        other_login:''
      },
      error:null,
      loaded:false,
      loading:false,
      other_login_items:[],
      other_login_btn_items:[],
      must_verify:false
    }
  },
  methods: {
    async postLogin(values){
        if(this.sending){
            return;
        }
        this.sending = true;
        //发送短信验证码
        let response
        try{
            response = await this.$request.post('/open/login',values);
        }catch(error){
            if (error.response) {
                response = error.response;
            }
        }
        if(response){
           const data = response.data;
            if(response.status==200){
                this.userStore.loginSuccess(data,this.$router);
            }else if(response.status==422){
                collect(data.errors).each((item,field) => {
                    if(field=='verify'){
                      this.must_verify = true;
                    }
                    let message = item;
                    if(typeof item!=='string'){
                        message = collect(item).implode(';');
                    }
                    this.$refs.form.setFieldError(field, message);
                });
                this.refreshCaptcha();
            }
        }
        this.sending = false;
    },
    async fethData(){
      this.loading = true;
      this.error = null;
      this.loaded = false;
      try {
        let res = await this.$request.get('/open/login');
        const data = res.data || {};
        this.other_login_items = collect(data.otherLogin || [])
        .filter((item)=>{return !item.button})
        .values()
        .all(); 
        this.other_login_btn_items = collect(data.otherLogin || [])
        .filter((item)=>{return item.button})
        .values()
        .all(); 
        this.must_verify = data.mustVerify || false;
        this.loaded = true;
      } catch (error) {
        this.error = error;
      }
      this.loading = false;
      setTimeout(()=>{
        collect(this.other_login_btn_items).each((item)=>{
          let key = 'other-'+item.type;
          let ref = this.$refs[key];
          if(ref && ref.length){
            ref[0].innerHTML = item.button;
          }
        });
      },50)
    },
    async refreshCaptcha(){
        this.$refs.captchaImg.refreshCaptcha();
    },

  },
  created(){
    this.fethData();
  }
}
</script>
